package com.woniuxy.base.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.base.mapper.BaseMaterialMapper;
import com.woniuxy.base.model.entity.BaseMaterial;
import com.woniuxy.base.model.entity.BaseMaterialRecord;
import com.woniuxy.base.service.BaseMaterialRecordService;
import com.woniuxy.base.service.BaseMaterialService;
import com.woniuxy.util.SnowflakeIdWorker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BaseMaterialServiceImpl implements BaseMaterialService {
    @Resource
    private BaseMaterialMapper baseMaterialMapper;

    @Resource
    private BaseMaterialRecordService recordService;

    @Override
    public Page<BaseMaterial> getAll(int current, int size) {
        return baseMaterialMapper.selectPage(new Page<>(current, size),null);
    }

    @Transactional
    @Override
    public Boolean update(BaseMaterial baseMaterial, String account) {
        BaseMaterial record = baseMaterialMapper.selectById(baseMaterial.getId());
        BaseMaterialRecord materialRecord = new BaseMaterialRecord();
        materialRecord.setType(record.getType())
                        .setCode(record.getCode()).setState(record.getState())
                        .setDescription(record.getDescription()).setUpdateTime(record.getAddTime())
                        .setMaterialId(record.getId()).setUpdatePerson(account);
        baseMaterialMapper.update(baseMaterial, new UpdateWrapper<BaseMaterial>().eq("id",baseMaterial.getId()));
        recordService.add(materialRecord);
        return true;
    }

    @Override
    public Boolean add(BaseMaterial baseMaterial) {
        baseMaterial.setCode(String.valueOf(SnowflakeIdWorker.newId()));
        baseMaterialMapper.insert(baseMaterial);
        return true;
    }

    @Override
    public Page<BaseMaterial> conditionSearch(BaseMaterial baseMaterial, Integer current, Integer size) {
        return baseMaterialMapper.selectPage(new Page<>(current,size),new QueryWrapper<BaseMaterial>(baseMaterial));
    }

    @Override
    public Page<BaseMaterial> keywordSearch(String keyword, Integer current, Integer size) {
        QueryWrapper<BaseMaterial> wrapper = new QueryWrapper<>();
        wrapper.like("type",keyword).or().like("description",keyword);
        return baseMaterialMapper.selectPage(new Page<>(current,size),wrapper);
    }

    @Override
    public List<BaseMaterialRecord> detail(Integer materialId) {
        return recordService.detail(materialId);
    }

    @Override
    public List<BaseMaterial> baseList() {
        return baseMaterialMapper.selectList(null);
    }

}
